import Tab from "../../components/Tab";
import Header from "../../components/Header";
import './index.scss'
import {Tabs} from "antd-mobile";
import RegionInner from "../../components/RegionInner";
import {useEffect, useState} from "react";
import {dictRegionList, regionDetail, relationArticleList, relationLiteratureList} from "../../api/api";

const Region = () => {
    // tab
    const [tabs, setTabs] = useState<Array<{ title: string, key: string }>>([]);

    // 区域数据
    const [data, setData] = useState<any>(null);

    // 当前选择项
    const [activeKey, setActiveKey] = useState<string>("");

    // 关联文献
    const [literatureData, setLiteratureData] = useState<Array<any>>([]);

    // 关联文章
    const [articleData, setArticleData] = useState<Array<any>>([]);
    // 区域详情
    const getData = () => {
        regionDetail(activeKey).then(r => {
            setData(r);
        })
    };

    useEffect(() => {
        dictRegionList().then(r => {
            let tabs = r.map((v: { id: string, name: string }, index: number) => {
                if (index === 0) {
                    setActiveKey(v.id)
                }
                return {
                    key: v.id,
                    title: v.name
                }
            });
            setTabs(tabs);
        });
    }, []);

    useEffect(() => {
        if (activeKey) {
            getData();
            relationLiteratureList(activeKey).then(r => {
                const data = r.map((v: { cover: { id: string, path: string } }) => {
                    return {
                        ...v,
                        cover_url: v.cover.path
                    }
                })
                setLiteratureData(data);
            });
            relationArticleList(activeKey).then(r => {
                const data = r.map((v: { cover: { id: string, path: string } }) => {
                    return {
                        ...v,
                        cover_url: v.cover.path
                    }
                })
                setArticleData(data);
            })
        }
    }, [activeKey]);


    return (
        <div className="region-box">
            <Header back={null} title="区域"/>
            <div>
                <Tabs activeKey={activeKey} onChange={(v: string) => setActiveKey(v)}>
                    {
                        tabs?.map(v => {
                            return (
                                <Tabs.Tab title={v.title} key={v.key}>
                                    <RegionInner id={activeKey} literatureData={literatureData}
                                                 articleData={articleData} data={data}/>
                                </Tabs.Tab>
                            )
                        })
                    }
                </Tabs>
            </div>
            <Tab/>
        </div>
    )
}

export default Region;